package cn.ifafu.ifafu.ui.main

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.core.net.toUri
import cn.ifafu.ifafu.R
import cn.ifafu.ifafu.bean.vo.MenuVO
import cn.ifafu.ifafu.constant.FEEDBACK_GROUP_ID
import cn.ifafu.ifafu.constant.FEEDBACK_GROUP_KEY
import cn.ifafu.ifafu.ui.about.AboutActivity
import cn.ifafu.ifafu.ui.comment.CommentActivity
import cn.ifafu.ifafu.ui.elective.ElectiveActivity
import cn.ifafu.ifafu.ui.examlist.ExamListActivity
import cn.ifafu.ifafu.ui.score.ScoreActivity
import cn.ifafu.ifafu.ui.timetable.TimetableActivity
import cn.ifafu.ifafu.ui.web.WebActivity
import cn.ifafu.ifafu.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import timber.log.Timber

class MainMenuHandler(private val context: Context) {

    /**
     * 处理Menu点击事件
     *
     * @return 处理成功返回true，否则返回false
     */
    fun handle(menu: MenuVO): Boolean {
        when (menu.id) {
            R.id.menu_exam_list -> startActivityByClazz(ExamListActivity::class.java)
            R.id.menu_score_list -> startActivityByClazz(ScoreActivity::class.java)
            R.id.menu_elective -> startActivityByClazz(ElectiveActivity::class.java)
            R.id.menu_schedule -> startActivityByClazz(TimetableActivity::class.java)
            R.id.menu_web -> startActivityByClazz(WebActivity::class.java)
            R.id.menu_repair -> openWebPage("报修服务", "http://hq.fafu.edu.cn/agent/app/index.php?i=144&c=entry&do=index&m=maihu_repair")
            R.id.menu_pd -> openWebPage("二手交易", "https://pd.qq.com/s/4vh9xzdus")
            R.id.menu_comment -> startActivityByClazz(CommentActivity::class.java)
            R.id.menu_feedback -> AppUtils.jumpToQQGroup(FEEDBACK_GROUP_KEY)
            R.id.menu_about_ifafu -> startActivityByClazz(AboutActivity::class.java)
            else -> return false
        }
        return true
    }

    private fun openWebPage(name: String, url: String) {
        try {
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            intent.data = url.toUri()
            context.startActivity(intent)
        } catch (e: Exception) {
            Timber.e(e, "打开失败: $name, $url")
            ToastUtils.showShort("打开失败, 请加群${FEEDBACK_GROUP_ID}反馈")
        }
    }

    private fun startActivityByClazz(clazz: Class<out Activity>) {
        val intent = Intent(context, clazz)
        context.startActivity(intent)
    }

}